<?php
include 'func.inc.php';
include("/var/www/html/new/com.inc.php");
include("/var/www/html/alipay/alipay.config.php");
include("/var/www/html/alipay/lib/alipay_notify.class.php");
include("/var/www/html/new/d/class/OrderRecord.php");

define('ACTION_MONEY_ADD',0);
define('ACTION_MONEY_CUT',1);
define('ERROR_LOG', '/var/www/html/new/d/logs/alipay_pc/err_log_'.date('ymd').'.txt');
define('OK_LOG', '/var/www/html/new/d/logs/alipay_pc/log_'.date('ymd').'.txt');
define('DATA_LOG', '/var/www/html/new/d/logs/alipay_pc/data_'.date('ymd').'.txt');

//计算得出通知验证结果
$alipayNotify = new AlipayNotify($alipay_config);
$verify_result = $alipayNotify->verifyNotify();
if($verify_result) {//验证成功
    //记录 POST 的数据
    write_logs(json_encode($_POST), OK_LOG);
    $out_trade_no = $_POST['out_trade_no'];// 商户订单号
    $trade_no = $_POST['trade_no']; // 支付宝交易号
    $trade_status = $_POST['trade_status'];// 交易状态

    if($_POST['trade_status'] == 'TRADE_FINISHED') {
        logResult("1:$trade_no:$out_trade_no:$trade_status\n");
    }
    else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
        //判断该笔订单是否在商户网站中已经做过处理
		$s = new SoapClient(null,array(
            "location" => "http://localhost/open/openService/pft_insideMX.php",
            "uri" => "www.16u.com?ac_16u={$GLOBALS['_ac']}|pw_16u={$GLOBALS['_pw']}|auth_16u=true")
        );
         
        $str=<<<SQL
select status,royalty_parameters,total_fee from pft_alipay_rec
WHERE out_trade_no='$out_trade_no' limit 1
SQL;
        $GLOBALS['le']->query($str);
        $GLOBALS['le']->fetch_assoc();
        $status=$GLOBALS['le']->f('status');
        $royalty_parameters=$GLOBALS['le']->f('royalty_parameters');
        $total_fee=$GLOBALS['le']->f("total_fee") * 100;
        if($GLOBALS['le']->f('status')!=1){
            $str=<<<SQL
update pft_alipay_rec set status=1,dtime=now(),`trade_no`='$trade_no'
WHERE out_trade_no='$out_trade_no' limit 1
SQL;
            $GLOBALS['le']->query($str);
            $ordern = $out_trade_no;
			
            $or=new OrderRecord($out_trade_no, $s);
			$orders=$or->info();
            //daction=1,取消订单不原路退回，$daction=0原路退回。TICKET_MACHINE为取票机标识——cgp@2015年8月25日16:13:11
            $daction = strpos($_POST['body'], 'TICKET_MACHINE')===false ? 1 : 0;
			total_fee($orders, $daction);
			
			$aid = (int)$orders['mainOrder']->UUaid;
			$mid = (int)$orders['mainOrder']->UUmid;
            fenRun($s,$out_trade_no,$aid, $mid, $total_fee,$orders,true);

            $ret = $s->Mod_Order_Status($out_trade_no,1,1);
            //演出订单更新座位状态
            // if((string)$orders['mainOrder']->UUp_type=='H')
            // {
                // $relation_info_req = http_build_query(array(
                    // 'Action'  => 'Relation_after_pay',
                    // 'Ordern'  => $out_trade_no,
                    // 'Fid'     => (int)$orders['mainOrder']->UUmid,
                // ));
                // file_get_contents('http://10.160.4.140/new/d/api/Product_check_h.php?'.$relation_info_req);
            // }
			
			// 支付后交互
			$tid = (int)$orders['mainOrder']->UUtid;
			$sql = "select Mpath,Mdetails from uu_jq_ticket where id=$tid limit 1";
			$GLOBALS['le']->query($sql);
			$GLOBALS['le']->fetch_assoc();
			if(($Mpath=$GLOBALS['le']->f('Mpath'))){
				
				$relation_info_req = http_build_query(array(
                    'Action'  => 'Relation_after_pay',
                    'Ordern'  => $out_trade_no,
                    'Fid'     => (int)$orders['mainOrder']->UUmid,
                ));
                file_get_contents($Mpath.'?'.$relation_info_req);
			}
			
            write_logs("更新订单状态|订单号[$out_trade_no]|返回代码[$ret]", OK_LOG);
            //更新远端订单号——pzp:因为会与接口的业务冲突，取消更新远端订单@15-07-23
//            $ret = $s->Remote_Ordernum_Update(serialize(array($out_trade_no=>'PC_ALIPAY_PFT_'.$_SERVER['REQUEST_TIME'])));
//            write_logs("更新远端订单号|订单号[$out_trade_no]|返回代码[]", OK_LOG);
            if ($orders['mainOrder']->UUordertel!='' && $orders['mainOrder']->UUordertel!='00000000000') {
                include '/var/www/html/new/d/class/OrderSmsManual.class.php';
                $smsManual  = new \PFT\SMS\OrderSmsManual($s);
                $ret = $smsManual->SendByOrderInfo($orders);
                if ($ret!=100) {
                    write_logs("短信发送失败|订单号[$out_trade_no]|返回代码[$ret]", ERROR_LOG);
                } else {
                    write_logs("短信发送成功|订单号[$out_trade_no]|返回代码[$ret]", OK_LOG);
                }
            }

            $request = array(
                'action' => 'send_alipass',
                'auth' => md5('RFGrfgY5CjVP8LcYsend_alipass'),
                'out_trade_no' => $out_trade_no,
                'title' => (string)$orders['mainOrder']->UUltitle,
                'begin_time' => strtotime($orders['mainOrder']->UUbegintime),
                'end_time' => strtotime($orders['mainOrder']->UUendtime) + 3600 * 24,
                'code' => (string)$orders['mainOrder']->UUcode
            );
            $request_data = base64_encode(json_encode($request));
            file_get_contents("http://121.41.120.34/pft/alipay_fuwuchuang/alipass.php?data=".$request_data);
        }
    }
    //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
    echo "success";        //请不要修改或删除
    logResult("2:$trade_no:$out_trade_no:$trade_status\n");
}
else {
    //验证失败
    echo "fail";
    logResult("3:$trade_no:$out_trade_no:$trade_status\n");
}

// 转分销分润
//         fenRun($s, $ordern, $aid, $mid, $total_fee, $orders, $to_pft, $p_type = 1)
function fenRun_bak20151010($s,$ordern,$aid, $mid,$total_fee,$orders,$to_pft){
    
//    $aid = (string)$orders['mainOrder']->UUaid;
//    $mid = (string)$orders['mainOrder']->UUmid;
    $add = 0;
    $cut = 1;
	
    // 非自供产品获取结算价
    if($aid!=$mid){
        $total_money = 0;
        $pid = (string)$orders['mainOrder']->UUpid;// 产品 id
        $begintime = (string)$orders['mainOrder']->UUbegintime;// 游玩时间价格
        $account = (string)$orders['mainOrder']->UUfromt;// 游玩时间价格
        $ret = $s->Dynamic_Price_And_Storage($account,$pid,$begintime,1,0,0,$aid);
        if($ret==105||$ret==1065){
            $total_money = $total_fee;
        }else{
            $obj = simplexml_load_string($ret);
            $total_money = (string)$obj->Rec->UUsprice * (int)$orders['mainOrder']->UUtnum;
        }
        if(count($orders['childOrder']) && $orders['mainOrder']->UUp_type!='F'){
            foreach($orders['childOrder'] as $key=>$child){
                $pid = (string)$child->UUpid;// 产品 id
                $ret = $s->Dynamic_Price_And_Storage($account,$pid,$begintime,1,0,0,$aid);
                if($ret!=105 && $ret!=1065){
                    $obj = simplexml_load_string($ret);
                    $total_money += (string)$obj->Rec->UUsprice * (int)$child->UUtnum;
                }
            }
        }
    }
    
    if($to_pft){
        //票付通总账号加钱——2015年4月13日11:56:33林农说要添加，宝椿提供的代码
        // 2015年9月1日14:44:50——取消管理员账号加钱
//        $s->PFT_Member_Fund_Modify(1, 0, $total_fee, $add, 0,null,0, 0,$ordern);
        // 支付给了票付通，最下级供应商加钱
        $s->PFT_Member_Fund_Modify($aid, 0, $total_fee, $add, 0,null,0, 1,$ordern);
    }


    // 产品多级销售分润
    $str="select aids_money from uu_order_fx_details where orderid='$ordern' limit 1";
    $GLOBALS['le']->query($str);
    $lirun = $GLOBALS['le']->fetch_assoc();
    if ($lirun['aids_money']){
        // 子票没有记录分润，获取子票价格
        $childMenoy = array();
        if(count($orders['childOrder']) && $orders['mainOrder']->UUp_type!='F'){
            foreach($orders['childOrder'] as $key=>$child){
                $aids = explode(',',(string)$child->UUaids);
                krsort($aids);
                $aids_price = explode(',',(string)$child->UUaids_price);
                krsort($aids_price);
                foreach($aids as $k=>$et){
                    if($k==0) break;// 最后一个不用操作了
                    $childMenoy[$et]+= $aids_price[$k-1] * (string)$child->UUtnum;
                }
            }
        }
        // 主订单的 aids
        $main_aids = explode(',',(string)$orders['mainOrder']->UUaids);
        $aids_money = unserialize($lirun['aids_money']);
        $opID = 0;
        foreach($aids_money as $row){
            $fid=$row[0];
            $action = ($row[2]==0) ? $cut : $add;//0减少,1增加和接口相反
            $Mmoney=$row[3];
            if($action==0){ // 加钱
                $ks = array_search($fid,$main_aids);
                $ks = $ks+1;
                $Mmoney += isset($childMenoy[$main_aids[$ks]]) ? $childMenoy[$main_aids[$ks]]:0;
            }else{
                $Mmoney += isset($childMenoy[$fid]) ? $childMenoy[$fid]:0;
            }

            if($row[1]==0){//信用额度
                $dmode = 1;
                $res = $s->PFT_Member_Fund_Modify($fid,$opID,$Mmoney,$action,$dmode,$row[4],0,2,$ordern);
            }else{//资金
                $dmode = 0;
                $res = $s->PFT_Member_Fund_Modify($fid,$opID,$Mmoney,$action,$dmode,NULL,0,0,$ordern);
            }
        }
    }
    return $total_money;// 返回上级利润
}

// 获取订单总价格，以分为单位
function total_fee_bak20151010($orders, $daction=0){
    $total_fee = 0;
    $aid = (string)$orders['mainOrder']->UUaid;
	$mid = (string)$orders['mainOrder']->UUmid;
	
    $total_fee=((string)$orders['mainOrder']->UUtprice * (string)$orders['mainOrder']->UUtnum);
    $ordernum = (string)$orders['mainOrder']->UUordernum;
    $str=<<<SQL
insert pft_member_alipay set fid=$mid,orderid='$ordernum',
total_fee='$total_fee',money='$total_fee',ali_account='',rectime=now(),
dtype=0,daction=$daction
SQL;
    $GLOBALS['le']->query($str);
            
    // 加上非套票的子票价格
    if(count($orders['childOrder']) && $orders['mainOrder']->UUp_type!='F'){
        foreach($orders['childOrder'] as $key=>$child){
            $tmp = (int)$child->UUtprice * (int)$child->UUtnum;
            $total_fee+=$tmp;
            $ordernum = (string)$child->UUordernum;
            $str=<<<SQL
INSERT pft_member_alipay set fid=$mid,orderid='$ordernum',
total_fee='$tmp',money='$tmp',ali_account='',rectime=now(),dtype=0,daction=$daction
SQL;
            $GLOBALS['le']->query($str);
        }
    }
    return $total_fee;
}


//function write_logs($txt,$file='/var/www/html/alipay/new_log.txt'){
//    $fp = fopen($file,"a");
//    flock($fp, LOCK_EX);
//    fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
//    flock($fp, LOCK_UN);
//    fclose($fp);
//}
?>